<template>
    <div class="page-root">
        <!-- 左右容器 - 强制并排 -->
        <div class="split-container">
            <!-- 左侧树形区域 -->
            <div class="left-panel">
                <el-card class="panel-card" style="max-height: 700px;overflow-y: auto;">

                    <el-tree :data="treeData" :props="treeProps" node-key="id" highlight-current
                        default-expanded-keys="['RAIDStorage0']" :current-node-key="currentKey"
                        @node-click="handleNodeClick" />
                </el-card>
            </div>

            <!-- 右侧表单区域 -->
            <div class="right-panel">
                <el-card class="panel-card">
                    <template #header>
                        <div class="panel-header">
                            <i class="el-icon-info"></i>
                            <span>RAID控制器信息</span>
                        </div>
                    </template>

                    <div class="form-content">
                        <div class="form-title">
                            <h3>控制器详情</h3>
                        </div>

                        <div class="form-grid">
                            <!-- 表单项 -->
                            <div class="form-item" v-if="detailInfo?.Name">
                                <label>名称</label>
                                <span>{{ detailInfo?.Name }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.Protocol">
                                <label>接口类型</label>
                                <span>{{ detailInfo?.Protocol }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.Revision">
                                <label>固件版本</label>
                                <span>{{ detailInfo?.Revision }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.MediaType">
                                <label>介质类型</label>
                                <span>{{ detailInfo?.MediaType }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.TemperatureCelsius">
                                <label>温度</label>
                                <span>{{ detailInfo?.TemperatureCelsius }}℃</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.FirmwareStatus">
                                <label>固件状态</label>
                                <span>{{ detailInfo?.FirmwareStatus }}℃</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.CapacityBytes">
                                <label>容量</label>
                                <span>{{ kbToTb(detailInfo?.CapacityBytes) }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.CapableSpeedGbs">
                                <label>支持的速率</label>
                                <span>{{ (detailInfo?.CapableSpeedGbs) }}Gbps</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.NegotiatedSpeedGbs">
                                <label>协商速率</label>
                                <span>{{ (detailInfo?.NegotiatedSpeedGbs) }}Gbps</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.PowerState">
                                <label>电源状态</label>
                                <span>{{ (detailInfo?.PowerState) }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.PatrolState">
                                <label>热备状态</label>
                                <span>{{ (detailInfo?.PatrolState) }}</span>
                            </div>
                            <!-- /PatrolState -->
                            <div class="form-item" v-if="detailInfo?.Type">
                                <label>类型</label>
                                <span>{{ detailInfo?.Type }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.HoursOfPoweredUp">
                                <label>累计通电时长</label>
                                <span>{{ detailInfo?.HoursOfPoweredUp }}h</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.RotationSpeedRPM">
                                <label>转速(RPM)</label>
                                <span>{{ detailInfo?.RotationSpeedRPM }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.LogicalType">
                                <label>逻辑类型</label>
                                <span>{{ detailInfo?.LogicalType }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.RebuildState">
                                <label>重构状态</label>
                                <span>{{ detailInfo?.RebuildState }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.EnclosureDeviceId">
                                <label>框ID</label>
                                <span>{{ detailInfo?.EnclosureDeviceId }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.SlotNumber">
                                <label>槽位ID</label>
                                <span>{{ detailInfo?.SlotNumber }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.FirmwareVersion">
                                <label>固件版本</label>
                                <span>{{ detailInfo?.FirmwareVersion }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.OOBSupport">
                                <label>支持带外管理</label>
                                <span>{{ detailInfo?.OOBSupport ? '是' : '否' }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.Health">
                                <label>健康状态</label>
                                <span class="status-normal">{{ detailInfo?.Health == 'OK' ||
                                    "Informational" == detailInfo.Health ? '正常' : '异常'
                                    }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.SupportedRAIDTypes">
                                <label>支持的RAID级别</label>
                                <span>{{ formatData(detailInfo?.SupportedRAIDTypes) }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.Mode">
                                <label>工作模式</label>
                                <span>{{ detailInfo?.Mode }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.MemorySizeMiB">
                                <label>内存大小</label>
                                <span>{{ detailInfo?.MemorySizeMiB }} MB</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.SupportedDeviceProtocols">
                                <label>设备接口</label>
                                <span>{{ detailInfo?.SupportedDeviceProtocols }} {{ detailInfo?.SpeedGbps }}G</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.SASAddress">
                                <label>SAS地址</label>
                                <span>{{ detailInfo?.SASAddress }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.HDDSupportStripeSizeBytes">
                                <label>支持的条带大小范围</label>
                                <span>{{ detailInfo?.HDDSupportStripeSizeBytes }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.CachePinnedState">
                                <label>Cache Pinned状态</label>
                                <span>{{ detailInfo?.CachePinnedState ? '是' : '否' }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.CopyBackState">
                                <label>回拷</label>
                                <span>{{ detailInfo?.CopyBackState ? '已启用' : '已禁用' }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.SmarterCopyBackState">
                                <label>SMART错误时回拷</label>
                                <span>{{ detailInfo?.SmarterCopyBackState ? '已启用' : '已禁用' }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.BootDevices">
                                <label>启动设备</label>
                                <span>{{ detailInfo?.BootDevices }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.JBODState">
                                <label>JBOD模式</label>
                                <span>{{ detailInfo?.JBODState ? '已启用' : '已禁用' }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.FirmwareVersion">
                                <label>配置版本</label>
                                <span>{{ detailInfo?.FirmwareVersion }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.MaintainPDFailHistory">
                                <label>物理盘故障记忆</label>
                                <span>{{ detailInfo?.MaintainPDFailHistory ? '已启用' : '已禁用' }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.CardManufacturer">
                                <label> 厂商 </label>
                                <span>{{ detailInfo?.CardManufacturer }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.CardModel">
                                <label> 设备型号 </label>
                                <span>{{ detailInfo?.CardModel }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.Manufacturer">
                                <label> 芯片厂商 </label>
                                <span>{{ detailInfo?.Manufacturer }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.Model">
                                <label> 芯片型号 </label>
                                <span>{{ detailInfo?.Model }}</span>
                            </div>

                            <div class="form-item" v-if="detailInfo?.SerialNumber">
                                <label> 序列号 </label>
                                <span>{{ detailInfo?.SerialNumber }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.AutoConfig">
                                <label> Auto Config </label>
                                <span>{{ detailInfo?.AutoConfig }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.PSOCFirmwareVersion">
                                <label> PSOC固件版本 </label>
                                <span>{{ detailInfo?.PSOCFirmwareVersion }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.PSOCHardwareVersion">
                                <label> PSOC硬件版本 </label>
                                <span>{{ detailInfo?.PSOCHardwareVersion }}</span>
                            </div>
                            <div class="form-item" v-if="detailInfo?.PSOCPartNumber">
                                <label> PSOC部件编码 </label>
                                <span>{{ detailInfo?.PSOCPartNumber }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="form-content" v-if="detailInfo?.BBU">
                        <div class="form-title">
                            <h3>BBU</h3>
                        </div>

                        <div class="form-grid">
                            <!-- 表单项 -->
                            <div class="form-item">
                                <label>名称</label>
                                <span>{{ detailInfo?.BBU?.Name }}</span>
                            </div>
                            <div class="form-item">
                                <label>状态</label>
                                <span>{{ detailInfo?.BBU?.State == "Enable" ? '在用' : '禁用' }}</span>
                            </div>
                            <div class="form-item">
                                <label>健康状态</label>
                                <span>{{ detailInfo?.BBU?.Health == 'Informational' ? '正常' : '异常' }}</span>
                            </div>

                        </div>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { SystemUserController } from '@/api/system/index';

// 树形配置
const treeProps = {
    label: 'name',
    id: "id",
    children: 'children'
};

const currentKey = ref('RAIDStorage0')
const detailInfo = ref({})

// 树形数据
const treeData = ref([]);

function kbToTb(kb, decimal = 9) {
    if (typeof kb !== 'number' || isNaN(kb)) {
        throw new Error('请输入有效的数字（KB）');
    }
    // 1 TB = 1024^3 KB = 1073741824 KB
    const tb = kb / (1024 ** 3) / 1000;
    // 保留指定小数位数（避免浮点数精度问题）
    return Number(tb.toFixed(decimal));
}

// 状态

const handleNodeClick = (data) => {
    console.log('选中节点:', data);
    if (data.id == "RAIDStorage0") {
        getNodeInfo()
    } else {
        if (data.id) {
            getNodeInfo2(data.id)
        } else {
            getNodeInfo2(data.Drives_ID)
        }

    }
};

function getNodeInfo2(val) {
    let params = {
        id: val
    }
    SystemUserController.getDrives(params).then(res => {
        detailInfo.value = JSON.parse(res.data)
        console.log(detailInfo.value)
    })
}

function formatData(val) {
    if (!val) {
        return ""
    }
    const result = `RAID(${val.map(item => item.replace('RAID', '')).join('/')})`;
    return result
}

function ViewsSummary() {
    SystemUserController.ViewsSummary().then(res => {


        let arr2 = JSON.parse(res.data).RaidControllers.concat(JSON.parse(res.data).Drives)
        let arr = convertToTree(arr2)
        treeData.value = JSON.parse(JSON.stringify(arr, null, 2))
        getNodeInfo()
    })
}

function getNodeInfo() {
    SystemUserController.getRAIDStorage0().then(res => {
        detailInfo.value = JSON.parse(res.data)
    })
}

/**
 * 将原始Raid控制器数据转换为标准树结构
 * @param {Array} originalData - 原始RaidControllers数组（即输入数据中的"RaidControllers"字段值）
 * @returns {Array} 标准树结构数组
 */
function convertToTree(originalData) {
    // 处理磁盘节点（叶子节点）
    function convertDrive(drive) {
        return {
            id: drive.Drives_ID, // 磁盘唯一标识
            name: drive.Name,    // 磁盘名称
            children: [],        // 磁盘无下级节点
            ...drive,            // 保留磁盘的其他原始属性（如CryptoEraseSupported）
            // 删除冗余字段（可选，根据需求保留）
            Drives_ID: drive.Drives_ID,
            Name: undefined
        };
    }

    // 处理卷节点（二级节点）
    function convertVolume(volume) {
        // 卷的子节点是其包含的磁盘
        const children = volume.Drives?.map(drive => convertDrive(drive)) || [];
        return {
            id: volume.Volumes_ID,  // 卷唯一标识
            name: volume.Name,      // 卷名称
            children: children,     // 卷的子节点（磁盘）
            ...volume,              // 保留卷的其他原始属性（如VolumeRaidLevel）
            // 删除冗余字段
            Volumes_ID: undefined,
            Name: undefined,
            Drives: undefined
        };
    }

    // 处理RAID控制器节点（根节点）
    function convertRaidController(controller) {
        // 控制器的子节点包括：其包含的卷 + 自身直接关联的磁盘
        const volumeChildren = controller.Volumes?.map(volume => convertVolume(volume)) || [];
        const driveChildren = controller.Drives?.map(drive => convertDrive(drive)) || [];
        const allChildren = [...volumeChildren, ...driveChildren];

        return {
            id: controller.RaidController_ID,  // 控制器唯一标识
            name: controller.Name,             // 控制器名称
            children: allChildren,             // 控制器的子节点（卷 + 磁盘）
            ...controller,                     // 保留控制器的其他原始属性（如Type、Mode）
            // 删除冗余字段
            RaidController_ID: undefined,
            Name: undefined,
            Volumes: undefined,
            Drives: undefined
        };
    }

    // 处理顶层数组，返回树结构
    return originalData.map(controller => convertRaidController(controller));
}


onMounted(() => {
    ViewsSummary();
})
</script>

<style>
/* 基础样式重置 - 确保布局不受默认样式影响 */
html,
body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    /* 禁止页面整体滚动 */
}
</style>

<style scoped>
/* 页面根容器 */
.page-root {
    width: 100%;
    height: 100vh;
    padding: 20px;
    box-sizing: border-box;
    background-color: #f5f7fa;
}

/* 左右分栏容器 - 核心控制 */
.split-container {
    display: flex;
    width: 100%;
    height: 100%;
    gap: 20px;
    /* 强制不换行，溢出时显示滚动条 */
    flex-wrap: nowrap;
    overflow: hidden;
}

/* 左侧面板 - 固定宽度 */
.left-panel {
    width: 280px;
    /* 禁止收缩和拉伸 */
    flex: 0 0 280px;
    height: 100%;
}

/* 右侧面板 - 自适应宽度 */
.right-panel {
    /* 占满剩余空间，禁止收缩 */
    /* flex: 1 0 auto; */
    height: 100%;
    min-width: 0;

    overflow-y: auto;
    /* 关键：允许内容超出时收缩 */
}

/* 卡片样式 */
.panel-card {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: none;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

/* 卡片头部 */
.panel-header {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    color: #333;
    font-size: 14px;
}

.panel-header .el-icon-info {
    color: #409eff;
    margin-right: 8px;
}

/* 树形组件样式 */
::v-deep .el-tree {
    padding: 10px;
    flex: 1;
    overflow-y: auto;
}

/* 表单内容区 */
.form-content {
    padding: 20px;
    flex: 1;
    max-height: 500px;
    overflow-y: scroll;
}

/* 表单标题栏 */
.form-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eee;
}

.form-title h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

/* 表单网格布局 */
.form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    /* 固定3列，确保布局稳定 */
    gap: 20px;
}

/* 表单项 */
.form-item {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.form-item label {
    font-size: 13px;
    color: #666;
    font-weight: 500;
}

.form-item span {
    font-size: 14px;
    color: #333;
}

/* 状态样式 */
.status-normal {
    color: #52c41a;
}
</style>